<template>
  <!-- <div class="container" style="width: 100%; height: 100%;"> -->
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span class="active">图片列表</span>
    </div>

    <el-row>
      <el-col :span="4">
        <span>位置：</span>
        <el-select v-model="query.services" placeholder="请选择服务范围" clearable>
          <el-option label="全部服务范围" value=""></el-option>
          <el-option v-for="item in serviceList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
        </el-select>
      </el-col>
      <el-col :span="8">
        <el-button type="primary" class="searchbtn" size="small" @click="search">查询</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="btns">
      <el-button type="primary" class="searchbtn" size="small" @click="handleAdd">添加</el-button>
      <el-button type="primary" class="searchbtn ico" size="small" @click="handleBatchDelete">批量删除</el-button>
    </el-row>

    <!--  表格 -->

    <BaseTable
      :is-show-selection="true"
      :tableColumn="tableColumn"
      :tableData="tableData"
      :loading="loading"
      @edit="handleClick"
      @delete="handleDelete"
      @selection-change="handleSelectionChange"
    >
      <template #options="{ row }">
        <el-button size="small" type="success" @click="handleEdit(row)">修改</el-button>
        <el-button size="small" @click="handleDelete(row)" type="danger">删除</el-button>
      </template>
    </BaseTable>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="query.page"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="query.psize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="counts"
    >
    </el-pagination>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="500px" @close="handleDialogClose">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="标题" :label-width="formLabelWidth" prop="title">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="位置" :label-width="formLabelWidth" prop="typeid">
          <el-select v-model="form.typeid" placeholder="请选择位置">
            <el-option v-for="item in serviceList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" :label-width="formLabelWidth" prop="picture">
          <el-upload
            class="avatar-uploader"
            ref="upload"
            action="/"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleFileChange"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.picture && !isLocalImage(form.picture)" :src="getFullImageUrl(form.picture)" class="avatar">
            <img v-else-if="tempImageUrl" :src="tempImageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
          <el-input-number v-model="form.sort" :min="0" label="排序"></el-input-number>
        </el-form-item>
        <el-form-item label="链接地址" :label-width="formLabelWidth" prop="url">
          <el-input v-model="form.url" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="enabled">
          <el-switch
            v-model="form.enabled"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949">
          </el-switch>
          <span style="margin-left: 10px">{{ form.enabled == 1 ? "启用" : "禁用" }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
  <!-- </div> -->
</template>

<script>
import { list, del, batchDelete, add } from '../api/advertisement'
import { getServiceList } from '../api/stores'
import BaseTable from '@/components/BaseTable.vue'
export default {
  name: 'AdvertisementView',
  components: {
    BaseTable,
  },
  data() {
    return {
      loading: true,
      query: {
        page: 1,
        psize: 5,
        key: '',
        services: '',
      },
      counts: 0,
      tableColumn: [
        {
          prop: 'id',
          label: 'id',
          width: 180,
        },
        {
          prop: 'title',
          label: '标题',
          width: 180,
        },
        {
          prop: 'typeName',
          label: '位置',
        },
        {
          prop: 'picture',
          label: '图片',
          slotname: 'picture'
        },
        {
          prop: 'sort',
          label: '排序',
        },
        {
          prop: 'enabled',
          label: '状态',
          slotname: 'status'
        },
        {
          prop: 'options',
          label: '操作',
          slotname: 'options',
        },
      ],
      gridData: [],
      dialogTableVisible: false,
      dialogFormVisible: false,
      form: {
        id: 0,
        title: '',
        picture: '',
        sort: 0,
        typeid: '',
        url: '',
        enabled: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        typeid: [
          { required: true, message: '请选择位置', trigger: 'change' }
        ],
        picture: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ]
      },
      serviceList: [], // 服务范围列表
      formLabelWidth: '120px',

      currentPage1: 5,
      currentPage2: 5,
      currentPage3: 5,
      currentPage4: 4,
      formInline: {
        user: '',
        region: '',
      },
      tableData: [],
      multipleSelection: [],
      
      // 上传相关配置
      imageUrl: process.env.VUE_APP_UPLOAD_BASE_URL || '',
      uploadUrl: (process.env.VUE_APP_API_BASE_URL || '') + '/api/upload',
      tempImageUrl: '', // 用于临时显示本地选择的图片
      tempFile: null // 用于存储待上传的文件
    }
  },

  computed: {
    dialogTitle() {
      return this.form.id === 0 ? '添加广告图片' : '修改广告图片'
    },
    uploadHeaders() {
      return {
        Authorization: localStorage.getItem('token') || ''
      }
    }
  },

  methods: {
    handleClick(row) {
      console.log('编辑操作:', row)
      // 这里可以添加编辑逻辑
    },
    handleAdd() {
      this.dialogFormVisible = true
      this.form = {
        id: 0,
        title: '',
        picture: '',
        sort: 0,
        typeid: '',
        url: '',
        enabled: 1
      }
      this.tempImageUrl = ''
      this.tempFile = null
    },
    handleEdit(row) {
      this.dialogFormVisible = true
      this.form = {
        id: row.id,
        title: row.title,
        picture: row.picture,
        sort: row.sort,
        typeid: row.typeid,
        url: row.url,
        enabled: row.enabled
      }
      this.tempImageUrl = ''
      this.tempFile = null
    },
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        await del({ id: row.id })
        await this.getList()
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        } else {
          console.error('删除失败:', error)
        }
      }
    },
    async handleBatchDelete() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一条记录!',
        })
        return
      }

      try {
        await this.$confirm(`此操作将永久删除选中的 ${this.multipleSelection.length} 条记录, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })

        // 提取选中项的ID数组
        const ids = this.multipleSelection.map((item) => item.id)

        // 调用批量删除接口
        await batchDelete({ ids })

        // 刷新列表
        await this.getList()

        this.$message({
          type: 'success',
          message: '批量删除成功!',
        })
      } catch (error) {
        if (error === 'cancel') {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        } else {
          console.error('批量删除失败:', error)
          this.$message({
            type: 'error',
            message: '批量删除失败!',
          })
        }
      }
    },
    async getList() {
      this.loading = true
      try {
        let {
          data: { counts, list: listData },
        } = await list(this.query)
        this.counts = counts
        this.tableData = listData
        this.loading = false
        console.log('获取到的数据:', listData)
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    onSubmit() {
      console.log('查询表单提交:', this.formInline)
      // 这里可以添加实际的查询逻辑
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log('选中项发生变化:', val)
    },
    handleSizeChange(val) {
      this.query.psize = val
      this.query.page = 1 // 重置到第一页
      this.getList()
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.getList()
    },
    search() {
      this.query.page = 1
      this.getList()
    },
    refreshList() {
      this.dialogVisible = false
      this.getList()
    },
    
    // 添加获取服务范围列表的方法
    async getServiceList() {
      try {
        const res = await getServiceList()
        this.serviceList = res.data.list
      } catch (error) {
        console.error('获取服务范围列表失败:', error)
      }
    },
    
    // 表单提交
    async submitForm() {
      // 先进行表单验证
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) {
        console.log('表单验证失败!')
        this.$message({
          type: 'warning',
          message: '请填写完整信息!'
        })
        return false
      }

      try {
        // 如果有本地图片需要上传
        if (this.tempFile) {
          // 先上传图片
          const picturePath = await this.uploadImage(this.tempFile)
          if (picturePath) {
            this.form.picture = picturePath
          } else {
            this.$message({
              type: 'error',
              message: '图片上传失败!'
            })
            return
          }
        }

        // 确保 typeid 是数字类型
        const formData = {
          ...this.form,
          typeid: Number(this.form.typeid)
        };

        // 提交表单数据
        const res = await add(formData)
        if (res.errCode === 10000) {
          this.$message({
            type: 'success',
            message: this.form.id === 0 ? '添加成功!' : '修改成功!'
          })
          this.dialogFormVisible = false
          this.getList()
        } else {
          throw new Error(res.errMsg || '操作失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message({
          type: 'error',
          message: error.message || '保存失败!'
        })
      }
    },
    
    // 上传相关方法
    // 处理文件选择变化
    handleFileChange(file) {
      // 创建本地预览
      if (file.raw) {
        this.tempFile = file.raw
        this.tempImageUrl = URL.createObjectURL(file.raw)
        // 设置表单字段触发验证
        this.form.picture = this.tempImageUrl
        this.$refs.form.validateField('picture')
      }
    },
    
    // 上传前检查
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    
    // 上传图片到服务器
    uploadImage(file) {
      return new Promise((resolve, reject) => {
        const formData = new FormData()
        formData.append('file', file)
        
        // 获取认证token
        const token = localStorage.getItem('token')
        
        // 发送上传请求
        fetch(this.uploadUrl, {
          method: 'POST',
          body: formData,
          headers: {
            'Authorization': token || ''
          }
        })
        .then(response => {
          if (!response.ok) {
            throw new Error('网络错误')
          }
          return response.json()
        })
        .then(res => {
          if (res.errCode === 10000) {
            resolve(res.data)
          } else {
            reject(new Error(res.errMsg || '上传失败'))
          }
        })
        .catch(error => {
          reject(error)
        })
      })
    },
    
    // 判断是否为本地图片
    isLocalImage(url) {
      return url.startsWith('blob:') || this.tempImageUrl === url
    },
    
    // 弹窗关闭时的处理
    handleDialogClose() {
      this.$refs.form.resetFields()
      this.tempImageUrl = ''
      this.tempFile = null
    },
    
    // 获取完整图片URL
    getFullImageUrl(url) {
      if (!url) return '';
      if (url.startsWith('http')) return url;
      return `${this.imageUrl}${url}`;
    }
  },

  created() {
    this.getList()
    this.getServiceList()
  },
}
</script>

<style lang="less" scoped>
@import url(../assets/css/search.less);

.ico {
  background-color: red;
}

.searchInp {
  width: 200px;
  margin-right: 10px;
}

.el-select {
  width: 200px;
  margin-right: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>